<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card shadow="always">
      <!-- 警告提示区域 -->
      <el-alert
        title="注意:只允许为三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      ></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row :gutter="20" class="gods_cate">
        <el-col :span="24">
          <span>选择商品分类:</span>
          <!-- 级联选择框选择商品分类 -->
          <el-cascader
            v-model="goodsCateId"
            :options="goodsCateList"
            :props="cascaderParams"
            @change="goodsCateIdChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisable"
            @click="showAddParamsDialog"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table
            :data="activeCateParamsList"
            border
            stripe
            style="width: 100%"
            v-show="goodsCateId.length === 3"
          >
            <!-- 展开行 -->
            <!-- 三元运算符很强大要习惯使用 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 占位 -->
                <div class="padding"></div>
                <el-tag
                  :key="item.attr_id"
                  v-for="item in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="ParamsTagClose(scope.row, item)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="paramsInputVisible"
                  v-model="paramsInputValue"
                  ref="paramsTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  size="small"
                  @click="showParamsInput"
                  class="button-new-tag"
                  >+ New Tag</el-button
                >
                <!-- 占位 -->
                <div class="padding"></div>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deletParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisable"
            @click="showAddParamsDialog"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table
            :data="staticAttr"
            border
            stripe
            style="width: 100%"
            v-show="goodsCateId.length === 3"
            max-height="540px"
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 占位 -->
                <div class="padding"></div>
                <el-tag
                  :key="item.attr_id"
                  v-for="item in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="ParamsTagClose(scope.row, item)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="paramsInputVisible"
                  v-model="paramsInputValue"
                  ref="paramsTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  size="small"
                  @click="showParamsInput"
                  class="button-new-tag"
                  >+ New Tag</el-button
                >
                <!-- 占位 -->
                <div class="padding"></div>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deletParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table></el-tab-pane
        >
      </el-tabs>
    </el-card>

    <!-- 添加动态参数和静态属性的对话框 -->
    <el-dialog
      :title="'添加' + addParamsLabel"
      :visible.sync="addParamsDialog"
      width="50%"
      @close="resetAdddParamsForm"
    >
      <el-form
        ref="addParamsForm"
        :model="addParamsValue"
        label-width="80px"
        :rules="addParamsFormRules"
      >
        <el-form-item :label="addParamsLabel" prop="attr_name">
          <el-input v-model="addParamsValue.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitAddParamsForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改' + addParamsLabel"
      :visible.sync="editParamsDialog"
      width="50%"
    >
      <el-form
        ref="editParamsForm"
        :model="editParamsValue"
        label-width="80px"
        :rules="addParamsFormRules"
      >
        <el-form-item :label="addParamsLabel" prop="attr_name">
          <el-input v-model="editParamsValue.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitEditParamsForm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 防抖策略控制器
var flag = null
export default {
  data() {
    return {
      // 商品分类列表
      goodsCateList: [],
      // 选中的值
      goodsCateId: [],
      // 级联选择器配置参数
      cascaderParams: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name'
      },
      // tabs切换配置参数
      // 值是被激活的页签名称
      activeName: 'many',
      // 控制添加按钮是否启用
      addBtndisabled: true,

      // 分类参数列表
      // 动态参数
      activeCateParamsList: [],
      // 静态属性
      staticAttr: [],

      // 静态动态控制添加参数对话框
      addParamsDialog: false,
      // 添加参数的表单数据
      addParamsValue: {
        attr_name: ''
      },
      // 添加参数表单的验证规则
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 1, max: 18, message: '长度在 1 到 18 个字符', trigger: 'blur' }
        ]
      },

      // 编辑参数的dialog对话框开关
      editParamsDialog: false,
      // 编辑参数表单
      editParamsValue: {},

      // 控制展开行input输入框是否可见
      paramsInputVisible: false,
      // 展开行input输入框的值
      paramsInputValue: ''
    }
  },
  methods: {
    // 获取商品分类列表
    async getGoodsCate() {
      const res = await this.$http.get('categories', {
        params: { type: 3 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.goodsCateList = res.data
    },
    // 商品分类级联选择框改变触发
    goodsCateIdChange(val) {
      this.getGoodsCateParams()
    },
    // tab切换功能
    handleTabClick() {
      this.getGoodsCateParams()
    },

    // 获取商品分类参数
    async getGoodsCateParams() {
      if (this.goodsCateId.length !== 3) {
        this.goodsCateId = []
        return this.$message.error('请选择三级商品分类')
      }
      // 根据所选分类id和选择的tabs发起axios请求
      const res = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 将attr_vals字符串转为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      })
      // 判断是静态还是动态
      if (this.activeName === 'many') {
        this.activeCateParamsList = res.data
      } else {
        this.staticAttr = res.data
      }
    },
    // 展示添加参数的对话框,静态和动态合并
    showAddParamsDialog() {
      this.addParamsDialog = true
    },
    // 重置AdddParamsForm表单
    resetAdddParamsForm() {
      this.$refs.addParamsForm.resetFields()
    },
    // 完成添加功能
    submitAddParamsForm() {
      // 对表单完成预校验
      this.$refs.addParamsForm.validate(async valid => {
        if (!valid) {
          return this.$message.error('表单验证出错')
        }
        // 对表单的值进行补充
        this.addParamsValue.attr_sel = this.activeName
        this.addParamsValue.attr_vals = ''
        // 发起axios请求
        const res = await this.$http.post(
          `categories/${this.goodsCateId[2]}/attributes`,
          this.addParamsValue
        )
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getGoodsCateParams()
        this.addParamsDialog = false
      })
    },

    // 展示editdialog的btn
    async showEditDialog(params) {
      const res = await this.$http.get(
        `categories/${this.goodsCateId[2]}/attributes/${params.attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // ...展开符可以用于深度克隆
      this.editParamsValue = res.data
      this.editParamsDialog = true
    },
    // 完成编辑功能
    submitEditParamsForm() {
      // 对表单进行预校验
      this.$refs.editParamsForm.validate(async valid => {
        if (!valid) {
          return this.message.error('表单校验错误')
        }

        // 发起请求
        const res = await this.$http.put(
          `categories/${this.editParamsValue.cat_id}/attributes/${this.editParamsValue.attr_id}`,
          this.editParamsValue
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getGoodsCateParams()
        this.editParamsDialog = false
      })
    },

    // 完成删除参数的功能
    async deletParams(id) {
      // 创建一个messageBox
      const val = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (val === 'cancel') {
        return this.$message('取消删除')
      }
      // 发起删除的axios请求
      const res = await this.$http.delete(
        `categories/${this.goodsCateId[2]}/attributes/${id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getGoodsCateParams()
    },

    // 添加展开行的数量
    // 按下enter和失去焦点都会触发,按下按钮会触发两次
    async handleInputConfirm(params) {
      // 防抖按钮
      if (!flag) {
        flag = 1
        // 判断输入框的值不为空
        if (this.paramsInputValue) {
          // 添加动态具体值
          var index = params.attr_vals.findIndex(item => {
            return item === this.paramsInputValue
          })
          if (index !== -1) {
            // 清空表单
            this.paramsInputValue = ''
            // 隐藏表单
            this.paramsInputVisible = false
            // 防抖策略控制器
            setTimeout(function() {
              flag = null
            }, 20)
            return this.$message.error('不能重复输入相同的值')
          }
          params.attr_vals.push(this.paramsInputValue.trim())
          // 发起axios请求
          this.editParams(params)
        }

        // 隐藏表单
        this.paramsInputVisible = false
        this.paramsInputValue = ''
        // 防抖策略控制器
        setTimeout(function() {
          flag = null
        }, 20)
      }
    },
    // 控制该展开行的input输入框的显示与隐藏
    showParamsInput() {
      this.paramsInputVisible = true
      this.$nextTick(_ => {
        this.$refs.paramsTagInput.$refs.input.focus()
      })
    },
    // 控制标签的删除按钮
    ParamsTagClose(params, TagVal) {
      var index = params.attr_vals.findIndex(item => {
        return item === TagVal
      })
      params.attr_vals.splice(index, 1)
      this.editParams(params)
    },

    // axios用于添加和删除具体的数据
    async editParams(params) {
      const res = await this.$http.put(
        `categories/${this.goodsCateId[2]}/attributes/${params.attr_id}`,
        {
          attr_name: params.attr_name,
          attr_sel: params.attr_sel,
          attr_vals: params.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
    }
  },
  mounted() {
    // 获取商品分类列表
    this.getGoodsCate()
  },
  computed: {
    // 控制添加按钮是否启用
    isBtnDisable() {
      if (this.goodsCateId.length === 3) {
        return false
      }
      return true
    },
    // 当前选中的三级商品分类的id
    cateId() {
      if (this.goodsCateId.length === 3) {
        return this.goodsCateId[2]
      }
      return null
    },
    // addParamsFormLable 合并// dialog title
    addParamsLabel() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.gods_cate {
  margin: 15px 0;
}
.el-cascader {
  width: 250px;
  margin-left: 15px;
}
.el-tag {
  margin: 30px 20px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 200px;
  margin-left: 10px;
  vertical-align: middle;
}
.padding {
  display: inline-block;
  margin: 0 50px;
}
.el-tag,
.input-new-tag {
  font-size: 14px;
}
</style>
